package edu.ecust.design.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class CharacterFilter implements Filter {

	public void destroy() {
	}

	public void doFilter(ServletRequest servletRequest,
			ServletResponse response, FilterChain chain) throws IOException,
			ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		try {
			String type = request.getContentType();
			String requestedWith = request.getHeader("x-requested-with");

			if ((requestedWith != null)
					&& ("XMLHttpRequest".equals(requestedWith))
					&& (type != null)
					&& (type.startsWith("application/x-www-form-urlencoded"))) {
				request.setCharacterEncoding("UTF-8");
				response.setCharacterEncoding("UTF-8");
			} else if (request.getContextPath().matches(".*/flex[/\\?].*")) {
				response.setContentType("application/xml;charset=utf-8");
				request.setCharacterEncoding("UTF-8");
			} else {
				response.setContentType("text/html;charset=utf-8");
				request.setCharacterEncoding("UTF-8");
			}
		} finally {
			chain.doFilter(request, response);
		}
	}

	public void init(FilterConfig arg0) throws ServletException {
	}
}
